package com.example.langchain4j.service;

import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.DocumentSplitter;
import dev.langchain4j.data.document.splitter.DocumentSplitters;
import dev.langchain4j.data.embedding.Embedding;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.model.embedding.EmbeddingModel;
import dev.langchain4j.store.embedding.EmbeddingStore;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class VectorizationService {

    @Resource
    private  EmbeddingModel embeddingModel;

    @Resource
    private  EmbeddingStore<TextSegment> embeddingStore;

    /**
     * 向量化文档内容
     */
    public void vectorizeDocument(Document document) {
        // 分割文档为段落

        String text = document.text();
        DocumentSplitter splitter = DocumentSplitters.recursive(800, 100);
        List<TextSegment> textSegments = splitter.split(Document.from(text));

//
//        // 为每个段落生成向量并存储
        List<Embedding> embeddings = embeddingModel.embedAll(textSegments).content();
        embeddingStore.addAll(embeddings, textSegments);

//        System.out.println("文档向量化完成，共处理 " + segments.size() + " 个段落");
    }

    /**
     * 清空所有向量
     */
    public void clearAll() {
        embeddingStore.removeAll();
        System.out.println("所有向量已清空");
    }
}
